$(function () {
    initUrlAndTitle();

    initOrderList();

    initOrderDetailList();

    initOrderDetaiToolbar();

    initAddOrdersDlg();

    initInOutStoreDialog();
})

//定义相关常量
//---------------订单类型-------------------------
var TYPE_PURCHASE = "1";   //采购退货
var TYPE_SELL = "2";       //销售订单

//---------------采购订单相关状态-------------------
var STATE_CREATE = "0";   //未审核
var STATE_CHECK = "1";    //已审核
var STATE_END = "2";      //已结束

var STATE_NOT_OUT = "0";   //未出库
var STATE_OUT = "1";       //已出库
var STATE_NOT_IN = "0";   //未入库
var STATE_IN = "1";       //已入库

var url = 'returnorders_listByPage';
var btnText = '';
var inoutTitle = '';
var isPurchaseOrder = Request['type'] === TYPE_PURCHASE;   //type=1 采购退货单
var isSellOrder = Request['type'] === TYPE_SELL;           //type=2 销售退货单


function initUrlAndTitle() {
    if (Request['oper'] === 'myorders') {
        if (isPurchaseOrder) {
            url = 'returnorders_myListByPage?t1.type=' + TYPE_PURCHASE + '&t1.state=' + STATE_CREATE;
            document.title = '我的采购退货单';
            btnText = '采购退货申请';
            inoutTitle = '出库';
            $('#addOrdersSupplier').html('供应商');
        }
        if (isSellOrder) {
            url = 'returnorders_myListByPage?t1.type=' + TYPE_SELL + '&t1.state=' + STATE_CREATE;
            document.title = '我的销售退货单';
            btnText = '销售退货录入';
            inoutTitle = '入库';
            $('#addOrdersSupplier').html('客户');
        }
    } else if (Request['oper'] === 'orders') {
        if (isPurchaseOrder) {
            url += '?t1.type=' + TYPE_PURCHASE;
            document.title = '采购退货单查询';
        }
        if (isSellOrder) {
            url += '?t1.type=' + TYPE_SELL;
            document.title = '销售退货单查询';
        }
    } else if (Request['oper'] === 'doCheck') {
        url += '?t1.type=' + TYPE_PURCHASE + '&t1.state=' + STATE_CREATE;
        document.title = '采购退货单审核';
    } else if (Request['oper'] === 'doOutStore') {
        url += '?t1.type=' + TYPE_PURCHASE + '&t1.state=' + STATE_CHECK;
        document.title = '采购退货单出库';
        inoutTitle = '出库';
    } else if (Request['oper'] === 'doInStore') {
        url += '?t1.type=' + TYPE_SELL + '&t1.state=' + STATE_NOT_IN;
        document.title = '销售退货单入库';
        inoutTitle = '入库';
    }
}


/**
 * 初始化退货订单列表
 */
function initOrderList() {
    $('#grid').datagrid({
        url: url,
        singleSelect: true,
        fitColumns: true,
        pagination: true,
        columns: getColumns(),
        onDblClickRow: function (rowIndex, rowData) {
            //显示详情
            $('#uuid').html(rowData.uuid);
            $('#supplierOrCustomer').html(isPurchaseOrder ? "供应商" : "客户");
            $('#waybillsn').html(rowData.waybillsn);
            $('#suppliername').html(rowData.supplierName);
            $('#state').html(getState(rowData.state));
            $('#creater').html(rowData.createName);
            $('#checker').html(rowData.checkName);
            $('#ender').html(rowData.endName);
            $('#createtime').html(formatDate(rowData.createtime));
            $('#checktime').html(formatDate(rowData.checktime));
            $('#endtime').html(formatDate(rowData.endtime));

            //加载明细列表
            $('#itemgrid').datagrid('loadData', rowData.returnorderdetails);

            //采购退货单已出库，显示运单详情按钮
            if (rowData.type === TYPE_PURCHASE && rowData.state === STATE_OUT) {
                showWaybill();
            } else {
                //打开订单详情
                $('#ordersDlg').dialog('open');
            }
        }
    })

}

function initOrderDetailList() {
    //订单明细列表
    $('#itemgrid').datagrid({
        fitColumns: true,
        singleSelect: true,
        columns: [[
            {field: 'uuid', title: '编号', width: 100},
            {field: 'goodsuuid', title: '商品编号', width: 100},
            {field: 'goodsname', title: '商品名称', width: 100},
            {field: 'price', title: '价格', width: 100},
            {field: 'num', title: '数量', width: 100},
            {field: 'money', title: '金额', width: 100},
            {field: 'state', title: '状态', width: 100, formatter: getDetailState}
        ]]
    });
}


function initOrderDetaiToolbar() {
    var toolbar = [];
    if (Request['oper'] === 'doCheck') {
        toolbar.push({
            text: '审核',
            iconCls: 'icon-search',
            handler: doCheck
        });
    } else if (Request['oper'] === 'doInStore' || Request['oper'] === 'doOutStore') {
        $('#itemgrid').datagrid({
            onDblClickRow: function (rowIndex, rowData) {
                $('#itemuuid').val(rowData.uuid);
                $('#goodsuuid').html(rowData.goodsuuid);
                $('#goodsname').html(rowData.goodsname);
                $('#goodsnum').html(rowData.num);

                //如果已入/出库，则变为只读,且隐藏按钮
                var state = rowData.state;
                var finishState = isPurchaseOrder ? STATE_OUT : STATE_IN;
                if (state === finishState) {
                    $('[name=storeuuid]').parent().css('display', 'none');
                    $('#storename').css('display', '');
                    showOrHideButton(false);
                    getStoreName(rowData.uuid, $('#storename'));
                } else {
                    $('[name=storeuuid]').parent().css('display', '');
                    $('#storename').css('display', 'none');
                    showOrHideButton(true);
                }

                //打开入库/出库窗口
                $('#itemDlg').dialog('open');
            }
        });
    } else if (Request['oper'] === 'myorders') {
        $('#grid').datagrid({
            toolbar: [{
                text: btnText,
                iconCls: 'icon-add',
                handler: function () {
                    $('#addOrdersDlg').dialog('open')
                }
            }]
        });
    }

    //默认都有导出按钮
    toolbar.push({
        text: '导出',
        iconCls: 'icon-excel',
        handler: doExport
    });
    $('#ordersDlg').dialog({toolbar: toolbar});
}


function getColumns() {
    var columns = null;
    if (isPurchaseOrder) {
        columns = [[
            {field: 'uuid', title: '编号', width: 100},
            {field: 'createtime', title: '生成日期', width: 100, formatter: formatDate},
            {field: 'checktime', title: '检查日期', width: 100, formatter: formatDate},
            {field: 'endtime', title: '结束日期', width: 100, formatter: formatDate},
            {field: 'type', title: '订单类型', width: 100, formatter: getOrderType},
            {field: 'createName', title: '下单员', width: 100},
            {field: 'checkName', title: '审核员', width: 100},
            {field: 'endName', title: '库管员', width: 100},
            {field: 'supplierName', title: isPurchaseOrder ? "供应商" : "客户", width: 100},
            {field: 'totalmoney', title: '合计金额', width: 100},
            {field: 'state', title: '订单状态', width: 100, formatter: getState},
            {field: 'waybillsn', title: '运单号', width: 100},
            {field: 'ordersuuid', title: '原订单编号', width: 100},
        ]];
    } else {
        columns = [[
            {field: 'uuid', title: '编号', width: 100},
            {field: 'createtime', title: '生成日期', width: 100, formatter: formatDate},
            {field: 'endtime', title: '结束日期', width: 100, formatter: formatDate},
            {field: 'type', title: '订单类型', width: 100, formatter: getOrderType},
            {field: 'createName', title: '下单员', width: 100},
            {field: 'endName', title: '库管员', width: 100},
            {field: 'supplierName', title: isPurchaseOrder ? "供应商" : "客户", width: 100},
            {field: 'totalmoney', title: '合计金额', width: 100},
            {field: 'state', title: '订单状态', width: 100, formatter: getState},
            {field: 'ordersuuid', title: '原订单编号', width: 100},
        ]];
    }

    return columns;
}


/**
 * 获取订单状态
 * 采购：0-未审核，1-已审核，2-已结束
 * @param value
 * @returns {*}
 */
function getState(value) {
    if (isPurchaseOrder) {
        switch (value * 1) {
            case 0:
                return '未审核';
            case 1:
                return '已审核';
            case 2:
                return '已结束';
            default:
                return ''
        }
    }
    if (isSellOrder) {
        switch (value * 1) {
            case 0:
                return '未入库';
            case 1:
                return '已入库';
            default:
                return '';
        }
    }
}

/**
 * 获取订单明细的状态
 * 采购单：0-未出库， 1-已出库
 * 销售单：0-未人库，1-已入库
 * @param value
 */
function getDetailState(value) {
    if (isPurchaseOrder) {
        switch (value * 1) {
            case 0:
                return '未出库';
            case 1:
                return '已出库';
            default:
                return ''
        }
    }
    if (isSellOrder) {
        switch (value * 1) {
            case 0:
                return '未入库';
            case 1:
                return '已入库';
            default:
                return ''
        }
    }
}


/**
 * 格式化日期
 * @param value
 */
function formatDate(value) {
    return new Date(value).Format('yyyy-MM-dd')
}


function getOrderType(value) {
    return value === TYPE_PURCHASE ? "采购退货单" : "销售退货单";
}


/**
 * 退货订单审核
 */
function doCheck() {
    $.messager.confirm("提示", "确认要审核吗?", function (yes) {
        if (yes) {
            $.ajax({
                url: 'returnorders_doCheck?id=' + $('#uuid').html(),
                type: 'post',
                dataType: 'json',
                success: function (result) {
                    if (result.success) {
                        //关闭订单详情对话框
                        $('#ordersDlg').dialog('close');
                        //刷新订单列表
                        $('#grid').datagrid('reload');
                    } else {
                        $.messager.alert('提示', result.message, 'info', null);
                    }
                }
            });
        }
    })
}


/**
 * 退货订单明细入库(销售单)
 */
function doInStore() {
    var formData = $('#itemForm').serializeJSON();
    if (!formData.storeuuid) {
        $.messager.alert('提示', '请选择仓库', 'info');
        return;
    }
    $.messager.confirm("提示", "确认要入库吗?", function (yes) {
        if (yes) {
            $.ajax({
                url: 'orderdetail_doInStore',
                type: 'post',
                data: formData,
                dataType: 'json',
                success: function (result) {
                    if (result.success) {
                        //关闭入库窗口
                        $('#itemDlg').dialog('close');

                        //刷新订单明细列表
                        var row = $('#itemgrid').datagrid('getSelected');   //获取当前操作的行
                        row.state = '1';                                    //修改其状态为已入库1
                        var data = $('#itemgrid').datagrid('getData');      //典型的刷新datagrid的技巧
                        $('#itemgrid').datagrid('loadData', data);

                        //如果所有明细均已入库，关闭订单详情窗口，并且刷新订单列表
                        var allIn = true;
                        $.each(data.rows, function (i, row) {
                            if (row.state * 1 === 0) {
                                allIn = false;
                                //跳出循环
                                return false
                            }
                        })
                        if (allIn) {
                            $('#ordersDlg').dialog('close');
                            $('#grid').datagrid('reload');
                        }
                    } else {
                        $.messager.alert('提示', result.message, 'info', function () {
                            if (result.message === '请先登录!') {
                                window.location.href = 'login.html';
                            }
                        })
                    }
                }
            });
        }
    })
}


/**
 * 退货订单明细出库(采购单)
 */
function doOutStore() {
    var formData = $('#itemForm').serializeJSON();
    if (!formData.storeuuid) {
        $.messager.alert('提示', '请选择仓库', 'info');
        return;
    }
    $.messager.confirm("提示", "确认要出库吗?", function (yes) {
        if (yes) {
            $.ajax({
                url: 'returnorderdetail_doOutStore',
                type: 'post',
                data: formData,
                dataType: 'json',
                success: function (result) {
                    if (result.success) {
                        //关闭出库窗口
                        $('#itemDlg').dialog('close');

                        //刷新订单明细列表
                        var row = $('#itemgrid').datagrid('getSelected');   //获取当前操作的行
                        row.state = '1';                                    //修改其状态为已出库1
                        var data = $('#itemgrid').datagrid('getData');      //典型的刷新datagrid的技巧
                        $('#itemgrid').datagrid('loadData', data);

                        //如果所有明细均已出库，关闭订单详情窗口，并且刷新订单列表
                        var allOut = true;
                        $.each(data.rows, function (i, row) {
                            if (row.state * 1 === 0) {
                                allOut = false;
                                //跳出循环
                                return false
                            }
                        })
                        if (allOut) {
                            $('#ordersDlg').dialog('close');
                            $('#grid').datagrid('reload');
                        }
                    } else {
                        $.messager.alert('提示', result.message, 'info', function () {
                            if (result.message === '请先登录!') {
                                window.location.href = 'login.html';
                            }
                        })
                    }
                }
            });
        }
    })
}


/**
 * 显示/隐藏入库/出库按钮
 * @param hasButtons
 */
function showOrHideButton(hasButtons) {
    if (hasButtons) {
        $('#itemDlg').dialog({
            height: 200,
            buttons: [
                {
                    text: inoutTitle,
                    iconCls: 'icon-save',
                    handler: function () {
                        if (isPurchaseOrder) {
                            doOutStore();
                        } else {
                            doInStore();
                        }
                    }
                }
            ]
        })
    } else {
        $('#itemDlg').dialog({
            height: 150,
            buttons: null
        })
    }
}


/**
 * 根据订单明细id查询所入的仓库
 * @param orderDetailUuid
 */
function getStoreName(orderDetailUuid, jqueryDom) {
    $.ajax({
        url: 'returnorderdetail_getStoreByID?id=' + orderDetailUuid,
        type: 'post',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                var name = result.data.name || "";
                jqueryDom.val(name);
            } else {
                $.messager.alert("提示", result.message, 'info', null);
            }
        }
    })
}


function initAddOrdersDlg() {
    //新增退货单窗口
    $('#addOrdersDlg').dialog({
        title: '新增退货单',
        width: 700,
        height: 400,
        modal: true,
        closed: true
    })
}


/**
 * //初始化入库/出库弹框
 */
function initInOutStoreDialog() {
    $('#itemDlg').dialog({
        width: 300,
        height: 200,
        title: inoutTitle,
        modal: true,
        closed: true
    });
}


/**
 * 执行导出功能
 */
function doExport() {
    $.download("returnorders_exportByTemplate", {"id": $('#uuid').html()});
}


function showWaybill() {
    var options = $('#ordersDlg').dialog('options');
    var toolbar = options.toolbar;
    toolbar.push({
        text: '运单详情',
        iconCls: 'icon-search',
        handler: function () {
            $.ajax({
                url: 'orders_waybilldetailList?waybillsn=' + $("#waybillsn").html(),
                type: 'post',
                dataType: 'json',
                success: function (result) {
                    if (result.success) {
                        var data = result.data || [];
                        $('#waybillDlg').dialog('open');
                        $('#waybillGrid').datagrid({
                            singleSelect: true,
                            fitColumns: true,
                            rownumbers: true,
                            data: data,
                            columns: [[
                                {field: 'exedate', title: '执行日期', width: 100},
                                {field: 'exetime', title: '执行时间', width: 100},
                                {field: 'info', title: '执行信息', width: 100}
                            ]]
                        })
                    } else {
                        $.messager.alert('提示', result.message, 'info', null);
                    }
                }
            });
        }
    })
    //重新渲染订单详情对话框
    $('#ordersDlg').dialog({
        toolbar: toolbar,
        onClose: function () {
            //每次关闭前删除运单详情按钮，保证界面上只出现一个运单详情按钮
            toolbar.pop();
            $('#ordersDlg').dialog({toolbar: toolbar, onClose: null});
            //重置运单号
            $('#waybillsn').html('');
        }
    })
    //打开订单详情
    $('#ordersDlg').dialog('open');
}


/**
 * 订单明细入库(销售退货单)
 */
function doInStore() {
    var formData = $('#itemForm').serializeJSON();
    if (!formData.storeuuid) {
        $.messager.alert('提示', '请选择仓库', 'info');
        return;
    }
    $.messager.confirm("提示", "确认要入库吗?", function (yes) {
        if (yes) {
            $.ajax({
                url: 'returnorderdetail_doInStore',
                type: 'post',
                data: formData,
                dataType: 'json',
                success: function (result) {
                    if (result.success) {
                        //关闭入库窗口
                        $('#itemDlg').dialog('close');

                        //刷新订单明细列表
                        var row = $('#itemgrid').datagrid('getSelected');   //获取当前操作的行
                        row.state = '1';                                    //修改其状态为已入库1
                        var data = $('#itemgrid').datagrid('getData');      //典型的刷新datagrid的技巧
                        $('#itemgrid').datagrid('loadData', data);

                        //如果所有明细均已入库，关闭订单详情窗口，并且刷新订单列表
                        var allIn = true;
                        $.each(data.rows, function (i, row) {
                            if (row.state * 1 === 0) {
                                allIn = false;
                                //跳出循环
                                return false
                            }
                        })
                        if (allIn) {
                            $('#ordersDlg').dialog('close');
                            $('#grid').datagrid('reload');
                        }
                    } else {
                        $.messager.alert('提示', result.message, 'info', null);
                    }
                }
            });
        }
    })
}